package com.ailanyin.gateway.service.impl;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ailanyin.common.core.constant.Constants;
import com.ailanyin.common.core.exception.CaptchaException;
import com.ailanyin.common.core.utils.StringUtils;
import com.ailanyin.common.core.web.domain.AjaxResult;
import com.ailanyin.common.redis.service.RedisService;
import com.ailanyin.gateway.config.properties.CaptchaProperties;
import com.ailanyin.gateway.service.ValidateCodeService;

/**
 * 验证码实现处理
 *
 * @author ailanyin
 */
@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private CaptchaProperties captchaProperties;

    /**
     * 生成验证码
     */
    @Override
    public AjaxResult createCaptcha() throws IOException, CaptchaException {
        AjaxResult ajax = AjaxResult.success();
        boolean captchaOnOff = captchaProperties.getEnabled();
        ajax.put("captchaOnOff", captchaOnOff);
        if (!captchaOnOff) {
            return ajax;
        }

        // 保存验证码信息
        String uuid = UUID.randomUUID().toString(true);

        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(150, 50);
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        redisService.setCacheObject(verifyKey, captcha.getCode(), Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        ajax.put("uuid", uuid);
        ajax.put("img", captcha.getImageBase64());
        return ajax;
    }

    /**
     * 校验验证码
     */
    @Override
    public void checkCaptcha(String code, String uuid) throws CaptchaException {
        if (StringUtils.isEmpty(code)) {
            throw new CaptchaException("验证码不能为空");
        }
        if (StringUtils.isEmpty(uuid)) {
            throw new CaptchaException("验证码已失效");
        }
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisService.getCacheObject(verifyKey);
        redisService.deleteObject(verifyKey);

        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException("验证码错误");
        }
    }
}
